package com.bitsbazaar.manager;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.bitsbazaar.dao.BaseDao;
import com.bitsbazaar.entity.Product;
import com.bitsbazaar.entity.User;

public class ProductManagerImpl implements ProductManager {
	
	private BaseDao dao;

	public BaseDao getDao() {
		return dao;
	}

	public void setDao(BaseDao dao) {
		this.dao = dao;
	}
	
	/**
	 * Saves the product 
	 * 
	 * @param	The product to save	
	 * @return 	The key(id) generated if success, -1 if failure/exception
	 * @author 	Rachit
	 */
	@Override
	public Long createProduct(Product product) {
		return dao.save(product);
		
	}

	/**
	 * @return 	a list of all products of the given sub category
	 * @author 	Rachit
	 */
	@Override
	public List<Product> getProductsBySubCat(Long subCatId) {
		@SuppressWarnings("unchecked")
		List<Product> obj = (List<Product>)(List<?>)dao.findByProperty(Product.class, "subcatId", subCatId);
		return obj;
	}
	
	/**
	 * @return a list of all products of the given sub category
	 * @author 	Rachit
	 */
	@Override
	public List<Product> getApprovedProductsBySubCat(Long subCatId, int approved) {
		@SuppressWarnings("unchecked")
		List<Product> obj = (List<Product>)(List<?>)dao.findByProperty(Product.class, "subcatId", subCatId,"approved",approved);
		return obj;
	}
	
	/**
	 * @return a list of all products
	 * @author 	Rachit
	 */
	@Override
	public List<Product> getApprovedProducts(int approved) {
		@SuppressWarnings("unchecked")
		List<Product> obj = (List<Product>)(List<?>)dao.findByProperty(Product.class,"approved",approved);
		return obj;
	}
	
	/**
	 * @return The product or null
	 * @author 	Rachit
	 */
	@Override
	public Product getProductById(Long id) {
		return (Product) dao.findById(Product.class, id);
	}

	/**
	 * Update the product
	 * @return true if success. false if failure,exception
	 * @author 	Rachit
	 */
	@Override
	public Boolean updateProduct(Product product) {
		return dao.update(product);
	}

	/**
	 * Delete a Product with the key id	 * 
	 * @return true if success, false if failure
	 * @author Rachit
	 */
	@Override
	public Boolean deleteProductById(Long id) {
		return dao.deleteById(Product.class, id);
	}
	
	@Override
	public Boolean adminAuthenticateByEmail(String email, String password){
		User user = getUserByEmail(email);
		if((user!=null)&&user.getPassword().equals(password)&&user.getType().equals("admin")){
			return true;
		}
		return false;
	}
	
	@Override
	public User getUserByEmail(String email) {
		User user = null;
		List<Object> list = dao.findByProperty(User.class, "email", email);
		if(list.size()>0)	
			user = (User)list.get(0);	
		return user;
	}
	
}